package org.mspring.mlog.web.security.interceptors;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.ServletException;

import org.mspring.mlog.web.security.interceptors.handlers.AbstractFailureHandler;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

/**
 * 
 * @author Gao Youbo
 * @since 2013年7月11日
 */
public class CustomSecurityInterceptor extends FilterSecurityInterceptor implements Filter {

    private List<AbstractSecurityInterceptor> interceptors;

    public void setInterceptors(List<AbstractSecurityInterceptor> interceptors) {
        this.interceptors = interceptors;
    }

    @Override
    public void invoke(FilterInvocation fi) throws IOException, ServletException {
        // TODO Auto-generated method stub
        if (interceptors != null && interceptors.size() > 0) {
            for (AbstractSecurityInterceptor interceptor : interceptors) {
                boolean hasPremission = interceptor.exec(fi);
                if (!hasPremission) { // 如果授权未通过
                    AbstractFailureHandler failureHandler = interceptor.getFailureHandler(fi);
                    if (failureHandler != null) { // 如果当前授权过滤器中，错误处理器纯在，那么进行错误处理
                        failureHandler.handler(fi);
                        return;
                    } else {// 跳出验证
                        throw new AccessDeniedException(" 没有权限访问！ ");
                    }
                }
            }
        }
        fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
    }

}
